home *** CD-ROM | disk | FTP | other *** search
- Path: hubcap.clemson.edu!hubcap!mjs
- From: mjs@hubcap.clemson.edu (M. J. Saltzman)
- Newsgroups: comp.lang.c
- Subject: Re: division problem
- Date: 31 Jan 96 15:24:23 GMT
- Organization: Clemson University
- Message-ID: <mjs.823101863@hubcap>
- References: <31097D77.11AA@rain.org> <26JAN199622082450@erich.triumf.ca> <4eh246$u6h@airdmhor.gen.nz> <4ej4ha$66@fountain.mindlink.net> <DLzvGG.2rn@uns.bris.ac.uk> <Pine.SOL.3.90.960130150923.21923F-100000@flute> <DM1KMy.G3p@uns.bris.ac.uk>
- NNTP-Posting-Host: hubcap.clemson.edu
-
- nathan@pact.srf.ac.uk (Nathan Sidwell) writes:
-
- |Darrell Grainger (a378grai@cdf.toronto.edu) wrote:
- |: On Tue, 30 Jan 1996, Nathan Sidwell (me) wrote:
-
- |: > Still no need to use floating point,
- |: > celcius = ((fahrenheit - 32) * 5 + 4) / 9
-
- |Adding 4 will give the correct rounding for values >= 0 or if division
- |truncates to most neg int.
- |Adding 5 will give incorrect rounding, whatever the domain of the dividend.
- |Subtracting 4 gives correct rounding for values < 0 if division rounds
- |towards zero.
-
- |[...]
-
- |For systems where division rounds towards zero, the expression should be
-
- |celcius = ((fahrenheit - 32) * 5 + (fahrenheit < 32 ? -4 : 4)) / 9
-
- |Depending on the target architecture and the strength of the compiler,
- |the conditional expression could be evaluated with bit masking operations.
-
- Hmm. This looks like a job for div()!
-
- The oft-neglected div() function has well-defined, portable semantics
- for division with negative operands, precisely so that a program does
- not have to determine which direction truncation takes--it always
- truncates toward zero. Unfortunately, IMO, this is the less desirable
- way to go, precisely because rounding now depends on the sign of the
- quotient. I guess it was intended to mimic FORTRAN's semantics.
-
- Thus:
-
- #include <stdlib.h>
-
- celcius = div((fahrenheit - 32) * 5 +
- (fahrenheit < 32 ? -4 : 4), 9).quot;
-
- works on any machine.
- --
- Matthew Saltzman
- Clemson University Math Sciences
- mjs@clemson.edu
-